package org.csu.mypetstore.web.servlets;

import org.csu.mypetstore.domain.Account;
import org.csu.mypetstore.domain.Item;
import org.csu.mypetstore.domain.Log;
import org.csu.mypetstore.domain.Product;
import org.csu.mypetstore.service.AccountService;
import org.csu.mypetstore.service.CatalogService;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.List;
//转到某个产品的界面，界面中含有其所有的item
public class ViewProductServlet extends HttpServlet {
    private static final String VIEW_PRODUCT = "/WEB-INF/jsp/catalog/Product.jsp";

    private String productId;

    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        doGet(request,response);
    }

    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        //productId
        productId = request.getParameter("productId");
        CatalogService catalogService = new CatalogService();
        //获取product
        Product product = catalogService.getProduct(productId);
        //获取itemList
        List<Item> itemList = catalogService.getItemListByProduct(productId);
        HttpSession session = request.getSession();
        session.setAttribute("product",product);
        session.setAttribute("itemList",itemList);


        Account account = (Account) session.getAttribute("account");

        if(account!=null){
            //时间
            SimpleDateFormat tempDate = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
            String datetime = tempDate.format(new java.util.Date());
            //信息
            String info = "查看"+productId+"界面";
            Log log = new Log(account.getUsername(),datetime,info);
            //添加log
            new AccountService().addLog(log);
        }


        request.getRequestDispatcher(VIEW_PRODUCT).forward(request,response);

    }
}
